package com.DosonLeung.homeschoolcommunication.Controllers;

import android.app.Activity;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.DosonLeung.homeschoolcommunication.App.SystemApplication;
import com.DosonLeung.homeschoolcommunication.Constant.SystemConstant;
import com.DosonLeung.homeschoolcommunication.Constant.UserConstant;
import com.DosonLeung.homeschoolcommunication.Models.ChatModel;
import com.DosonLeung.homeschoolcommunication.R;
import com.DosonLeung.homeschoolcommunication.SQLite.MembersDB;
import com.DosonLeung.homeschoolcommunication.Services.MainBinder;
import com.DosonLeung.homeschoolcommunication.Utils.RecordUtil;
import com.DosonLeung.homeschoolcommunication.Utils.StorageUtil;
import com.DosonLeung.homeschoolcommunication.Views.ChatLayout;
import com.DosonLeung.homeschoolcommunication.Views.ChatScroll;


/**
 * Created by DosonLeung on 2014/10/22.
 */
public class ChatActivity extends Activity {

    public ChatActivity self = this;
    public ChatModel chatModel;
    private Handler chatHandler;
    MainBinder serviceBinder;
    Intent serviceIntent;
    Handler serviceHandler;
    ServiceConnection conn;
    LinearLayout indexTop;
    LinearLayout typeWidgets;
    LinearLayout chatFunction;
    LinearLayout chatLevel;
    FrameLayout important;
    FrameLayout ordinary;
    FrameLayout routine;
    FrameLayout cancel;
    ChatScroll chatScroll;
    ImageView call;
    Button addBtn;
    Button sendMessage;
    Button takePicture;
    Button openAlbum;
    Button recordVoice;
    Button startRecord;
    TextView importantLevel;
    TextView ordinaryLevel;
    TextView routineLevel;
    TextView cancelLevel;
    ChatLayout chatLayout;
    LinearLayout chatBack;
    EditText msgText;
    Boolean ifAdd;
    Boolean ifEdit;
    TextView topContentName;
    String level = "0";
    String genre = "";

    SystemApplication app;
    private String target;
    private String avatar_path;
    private boolean tab;
    private boolean type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_activity);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        target = bundle.getString("target");//班级cid＋uid，个人uid,群发信息是“groupchat”
        app = (SystemApplication)getApplication();
        tab = bundle.getBoolean("tab");//群发是false
        type = bundle.getBoolean("type");//群发是false
        avatar_path = bundle.getString("avatar_path");
        initWidget();
        initHandler();
        chatModel = new ChatModel(this, target, avatar_path, chatLayout, type);//班级cid＋uid，个人uid,群发信息是“groupchat”
        chatScroll.init(chatModel);
        bindMainService();
    }

    //与现有的MainService绑定
    private void bindMainService() {
        serviceIntent = new Intent();
        serviceIntent.setAction("com.DosonLeung.homeschoolcommunication.Services.BIND_SERVICE");
        conn = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                serviceBinder = (MainBinder) service;
                serviceHandler = serviceBinder.getServiceHandler();
                ((MainBinder) service).setChatHandler(getChatHandler());
                try {
                    //startServicehou,尝试通过handler与service握手
                    serviceHandler.sendEmptyMessage(0x101);
                    chatModel.setServiceHandler(serviceHandler);
                } catch (NullPointerException e) {
                    e.printStackTrace();
                }
            }
            //与Service断开连接只有退出程序或者注销
            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e("MainActivity:", "Disconnected with MainService!");
            }
        };
        boolean status = bindService(serviceIntent, conn, Service.BIND_AUTO_CREATE);
        if (!status)
            Toast.makeText(self, "bindService failed!", Toast.LENGTH_SHORT).show();
    }

    private void initWidget() {
        typeWidgets = (LinearLayout) findViewById(R.id.type_widgets);
        chatFunction = (LinearLayout) findViewById(R.id.chat_function);
        if (UserConstant.USER_CHARACTER.equals("patriarch")) {
            if (type)
                typeWidgets.setVisibility(View.GONE);
            else
                typeWidgets.setVisibility(View.VISIBLE);
        } else {
            typeWidgets.setVisibility(View.VISIBLE);
        }
        call = (ImageView) findViewById(R.id.chat_call);
        chatLevel = (LinearLayout) findViewById(R.id.chat_level);
        chatLevel.setVisibility(View.GONE);
        chatScroll = (ChatScroll) findViewById(R.id.chat_scroll);
        important = (FrameLayout) findViewById(R.id.important);
        ordinary = (FrameLayout) findViewById(R.id.ordinary);
        routine = (FrameLayout) findViewById(R.id.routine);
        cancel = (FrameLayout) findViewById(R.id.cancel);
        indexTop = (LinearLayout) findViewById(R.id.index_top);
        addBtn = (Button) findViewById(R.id.chat_add_btn);
        msgText = (EditText) findViewById(R.id.edit_message);
        sendMessage = (Button) findViewById(R.id.send_message);
        takePicture = (Button) findViewById(R.id.take_picture);
        openAlbum = (Button) findViewById(R.id.open_album);
        recordVoice = (Button) findViewById(R.id.record_voice);
        chatLayout = (ChatLayout) findViewById(R.id.chat_list);
        startRecord = (Button) findViewById(R.id.start_record);
        chatBack = (LinearLayout) findViewById(R.id.chat_back_btn);
        topContentName = (TextView) findViewById(R.id.top_content_name);
        importantLevel = (TextView) findViewById(R.id.important_level);
        ordinaryLevel = (TextView) findViewById(R.id.ordinary_level);
        routineLevel = (TextView) findViewById(R.id.routine_level);
        cancelLevel = (TextView) findViewById(R.id.cancel_level);
        important.setBackgroundColor(getResources().getColor(R.color.transparent));
        ordinary.setBackgroundColor(getResources().getColor(R.color.transparent));
        routine.setBackgroundColor(getResources().getColor(R.color.transparent));
        cancel.setBackgroundColor(getResources().getColor(R.color.transparent));
        final MembersDB membersDB = new MembersDB(self, StorageUtil.getChatDir().toString() + "/" + "members.db3", 1);
        if(target.equals("groupchat")){
            int size = app.getTargetList().size();
            String names = "";
            for(int i = 0;i < size;i++){
                names += membersDB.getElementByUid("name", app.getTargetList().get(i))+"、";
            }
            if(names.length()>10){
                names = names.substring(0,7)+"...";
            }
            topContentName.setText(names);
        }else{
            topContentName.setText(membersDB.getElementByUid("name", target));
        }
        ifAdd = false;
        ifEdit = true;

        final Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                Bundle bundle = msg.getData();
                switch (msg.what) {
                    case 0x001://level is 1
                        handleSend(bundle);
                        break;
                    case 0x002:
                        handleSend(bundle);
                        break;
                    case 0x003:
                        handleSend(bundle);
                        break;
                }
            }

            public void handleSend(Bundle bundle) {
                if (bundle.getString("genre").equals("text")) {
                    chatModel.sendMessage(msgText.getText().toString(), level);
                    msgText.setText("");
                    level = "0";
                } else if (bundle.getString("genre").equals("takePic")) {
                    chatModel.getPhotoFromCamera(self);
                } else if (bundle.getString("genre").equals("openAlbum")) {
                    chatModel.getPhotoFromAlbum(self);
                } else if (bundle.getString("genre").equals("record")) {
                    chatFunction.setVisibility(View.GONE);
                    ifAdd = false;
                    msgText.setVisibility(View.GONE);
                    startRecord.setVisibility(View.VISIBLE);
                }
            }
        };

        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pressAddBtn();
            }
        });

        msgText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                if (i == EditorInfo.IME_ACTION_SEND) {
                    chatModel.sendMessage(msgText.getText().toString(), level);
                    msgText.setText("");
                }
                return false;
            }
        });

        msgText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                chatFunction.setVisibility(View.GONE);
                ifAdd = false;
            }
        });

        msgText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chatFunction.setVisibility(View.GONE);
                ifAdd = false;
                chatLayout.smoothScrollToButtom();
            }
        });

        sendMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserConstant.USER_CHARACTER == "teacher" && msgText.length() != 0 && (type||target.equals("groupchat")) && level.equals("0")) {
                    Toast.makeText(self, "请选择消息类型", Toast.LENGTH_SHORT).show();
                    InputMethodManager m = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    m.hideSoftInputFromWindow(ChatActivity.this.getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    chatLevel.setVisibility(View.VISIBLE);
                    genre = "text";
                } else {
                    chatModel.sendMessage(msgText.getText().toString(), level);
                    msgText.setText("");
                    chatLevel.setVisibility(View.GONE);
                }
            }
        });

        takePicture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserConstant.USER_CHARACTER == "teacher" && (type||target.equals("groupchat")) && level.equals("0")) {
                    Toast.makeText(self, "请选择消息类型", Toast.LENGTH_SHORT).show();
                    chatLevel.setVisibility(View.VISIBLE);
                    genre = "takePic";
                } else {
                    chatModel.getPhotoFromCamera(self);
                }
            }
        });

        openAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserConstant.USER_CHARACTER == "teacher" && (type||target.equals("groupchat")) && level.equals("0")) {
                    Toast.makeText(self, "请选择消息类型", Toast.LENGTH_SHORT).show();
                    chatLevel.setVisibility(View.VISIBLE);
                    genre = "openAlbum";
                } else {
                    chatModel.getPhotoFromAlbum(self);
                }
            }
        });

        recordVoice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (UserConstant.USER_CHARACTER == "teacher" && (type||target.equals("groupchat")) && level.equals("0")) {
                    Toast.makeText(self, "请选择消息类型", Toast.LENGTH_SHORT).show();
                    chatLevel.setVisibility(View.VISIBLE);
                    genre = "record";
                } else {
                    chatFunction.setVisibility(View.GONE);
                    ifAdd = false;
                    msgText.setVisibility(View.GONE);
                    startRecord.setVisibility(View.VISIBLE);
                }
            }
        });

        startRecord.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                voiceRecordMotionEventHandler(motionEvent);
                return true;
            }
        });

        importantLevel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Message msg = new Message();
                important.setBackgroundColor(getResources().getColor(R.color.important));
                ordinary.setBackgroundColor(getResources().getColor(R.color.transparent));
                routine.setBackgroundColor(getResources().getColor(R.color.transparent));
                cancel.setBackgroundColor(getResources().getColor(R.color.transparent));
                chatLevel.setVisibility(View.GONE);
                level = "1";
                msg.what = 0x001;
                Bundle bundle = new Bundle();
                bundle.putString("genre", genre);
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
        });

        ordinaryLevel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Message msg = new Message();
                important.setBackgroundColor(getResources().getColor(R.color.transparent));
                ordinary.setBackgroundColor(getResources().getColor(R.color.ordinary));
                routine.setBackgroundColor(getResources().getColor(R.color.transparent));
                cancel.setBackgroundColor(getResources().getColor(R.color.transparent));
                level = "2";
                chatLevel.setVisibility(View.GONE);
                msg.what = 0x002;
                Bundle bundle = new Bundle();
                bundle.putString("genre", genre);
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
        });

        routineLevel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Message msg = new Message();
                important.setBackgroundColor(getResources().getColor(R.color.transparent));
                ordinary.setBackgroundColor(getResources().getColor(R.color.transparent));
                routine.setBackgroundColor(getResources().getColor(R.color.routine));
                cancel.setBackgroundColor(getResources().getColor(R.color.transparent));
                level = "3";
                chatLevel.setVisibility(View.GONE);
                msg.what = 0x003;
                Bundle bundle = new Bundle();
                bundle.putString("genre", genre);
                msg.setData(bundle);
                handler.sendMessage(msg);
            }
        });

        cancelLevel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                important.setBackgroundColor(getResources().getColor(R.color.transparent));
                ordinary.setBackgroundColor(getResources().getColor(R.color.transparent));
                routine.setBackgroundColor(getResources().getColor(R.color.transparent));
                cancel.setBackgroundColor(getResources().getColor(R.color.press_record));
                chatLevel.setVisibility(View.GONE);
                level = "0";
                chatLevel.setVisibility(View.GONE);
            }
        });

        chatBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = getIntent();
                intent.putExtra("chat", true);
                setResult(SystemConstant.CHAT_CODE, intent);
                finish();
            }
        });

        if(type||target.equals("groupchat"))
            call.setVisibility(View.GONE);
        else
        call.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String strMobile = membersDB.getElementByUid("phone", target);
                //此处应该对电话号码进行验证。。
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + strMobile));
                startActivity(intent);
            }
        });
    }

    /**
     * 0x100 收到来自Service握手的消息
     * 0x200 收到来自MainService的提醒（有新消息）
     * 0x205 表示Socket消息发送成功(text类型)
     * 0x206 表示Socket消息发送成功(image类型)
     * 0x207 表示Socket消息发送成功(audio类型)
     * 0x400 收到来自MainService的提醒(网络异常)
     * 0x404 消息发送失败
     * *
     */
    private void initHandler() {
        chatHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case 0x100:
                        Log.e("ChatActivity", "service get chatHandler successfully!");
                        serviceHandler.sendEmptyMessage(0x503);
                        break;
                    case 0x200:
                        chatModel.notifyAllViews();
                        break;
                    case 0x202:
                        break;
                    case 0x205:
                        if(target.equals("groupchat"))
                            Toast.makeText(self,"群发消息成功！",Toast.LENGTH_SHORT).show();
                        break;
                    case SystemConstant.UPLOAD_IMAGE_SUCCESS:
                        break;
                    case SystemConstant.UPLOAD_AUDIO_SUCCESS:
                        break;
                    case 0x404:
                        Toast.makeText(self, "发送失败", Toast.LENGTH_SHORT).show();
                        Log.e("ChatActivity", "Network is unavailable!");
                        break;
                }
            }
        };

    }

    private void voiceRecordMotionEventHandler(MotionEvent motionEvent) {
        int action = motionEvent.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                RecordUtil.startRecording(this, chatModel.getMHandler(), "me");
                startRecord.setText("松开停止录音");
                startRecord.setBackgroundColor(getResources().getColor(R.color.press_record));
                break;
            case MotionEvent.ACTION_UP:
                Log.e("Action = ", "up");
                startRecord.setText("点击开始录音");
                startRecord.setBackgroundColor(getResources().getColor(R.color.main_background));
                RecordUtil.stopRecording();
                chatModel.sendVoice(RecordUtil.voicePath, level);
                level = "0";
                break;
            case MotionEvent.ACTION_MOVE:
                Log.e("Action = ", "move");
                break;
            case MotionEvent.ACTION_CANCEL:
                break;
            default:
                break;
        }
    }

    private void pressAddBtn() {
        if (!ifAdd) {
            if (startRecord.getVisibility() == View.VISIBLE) {
                startRecord.setVisibility(View.GONE);
                msgText.setVisibility(View.VISIBLE);
            } else if (startRecord.getVisibility() == View.GONE) {
                InputMethodManager m = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                m.hideSoftInputFromWindow(ChatActivity.this.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
            chatFunction.setVisibility(View.VISIBLE);
            ifAdd = true;
        } else {
            chatLevel.setVisibility(View.GONE);
            chatFunction.setVisibility(View.GONE);
            ifAdd = false;
        }
    }

    public Handler getChatHandler(){
        return chatHandler;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = getIntent();
            Bundle data = new Bundle();
            data.putBoolean("chat", true);
            intent.putExtras(data);
            setResult(SystemConstant.CHAT_CODE, intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //Activity回调，接收从上一个Activity返回的结果
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            String url;
            switch (requestCode) {
                case SystemConstant.GET_PHOTO_FROM_CAMERA:
                    url = data.getStringExtra("camera");
                    chatModel.photo = true;
                    chatModel.sendPhotoFromCamera(StorageUtil.getCameraDir() + "/" + url, level);
                    level = "0";
                    break;
                case SystemConstant.GET_PHOTO_FROM_ALBUM:
                    url = data.getStringExtra("album");
                    chatModel.photo = false;
                    chatModel.sendPhotoFromAlbum(url, level);
                    level = "0";
                    break;
                default:
                    break;
            }
        }
        level = "0";
    }

    @Override
    public void onRestart() {
        level = "0";
        super.onRestart();
        chatModel.notifyAllViews();
        serviceHandler.sendEmptyMessage(0x503);
    }

    //当ChatActivity处于后台或者不可见时，向Service发送信号
    @Override
    public void onPause() {
        serviceHandler.sendEmptyMessage(0x501);
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (chatModel != null) {
            chatModel.closeDBHelper();
            chatModel = null;
        }
        serviceHandler.sendEmptyMessage(0x400);
        unbindService(conn);
        super.onDestroy();
    }
}
